package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

//@Component
@Slf4j
public class OrdersTask {
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理超时未支付的订单
     */
//    @Scheduled(cron = "0 0/1 * * * ?")
    public void processTimeOutOrders(){

        //1.查询超时未支付的订单
        LocalDateTime time = LocalDateTime.now().minusMinutes(15); //15分钟前的时间
        List<Orders> ordersList = orderMapper.queryTimeOutOrders(Orders.PENDING_PAYMENT,time);
        //获取需要处理订单id
        List<Long> idList = ordersList.stream().map(Orders::getId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(ordersList)) {
//            //遍历每个订单设置订单状态信息
//            ordersList.forEach(x->{
//                        x.setCancelReason("超时未支付");
//                        x.setCancelTime(LocalDateTime.now());
//                        x.setStatus(Orders.CANCELLED);
//                //3. 更新每个订单
//                orderMapper.updateStatus(x);
//                    });
            orderMapper.updateBatch(LocalDateTime.now(),null,Orders.CANCELLED,"超时未支付，自动取消",idList);
            log.info("处理超时未支付的订单完成...." + LocalDateTime.now());
        }else{
            log.info("没有超时的订单");
        }
    }

    /**
     * 处理长时间派送中的订单
     */
//    @Scheduled(cron = "0 0/1 * * * ?")
    public void complete(){

        //1.查询派送超过一小时的订单
        LocalDateTime time = LocalDateTime.now().minusHours(1); //一小时前的时间
        List<Orders> ordersList = orderMapper.queryTimeOutOrders(Orders.DELIVERY_IN_PROGRESS,time);
        //获取需要修改的订单id
        List<Long> idList = ordersList.stream().map(Orders::getId).collect(Collectors.toList());

        if (CollectionUtils.isNotEmpty(ordersList)) {
            //遍历每个订单设置订单状态信息
//            ordersList.forEach(x->{
//                x.setCancelReason("派送完成");
//                x.setCancelTime(LocalDateTime.now());
//                x.setStatus(Orders.COMPLETED);
                //3. 更新每个订单
//            orderMapper.updateStatus(x);
//        });

            //批量更新订单
            orderMapper.updateBatch(null,LocalDateTime.now(),Orders.CANCELLED,null,idList);



            log.info("处理长时间派送中的订单...." + LocalDateTime.now());
        }else{
            log.info("没有长时间派送的订单");
        }
    }

}
